<template>
  <transition name="modal-fade">
    <div class="chat-message ai-message">
      <div v-if="visible" class="ai-chat-modal">
        <!-- 顶部栏 -->
        <div class="chat-header">
          <button class="drawer-btn" @click="openDrawer" title="打开侧边栏">
            📑
            <span class="tooltip">打开侧边栏</span>
            <!-- 提示文本 -->
          </button>
          <button @click="createNewChat" class="new-chat-btn" title="新建聊天">
            +
            <span class="tooltip">新建聊天</span>
            <!-- 新建聊天按钮提示 -->
          </button>
          <span class="ai-title">AI助手</span>
          <button class="close-btn" @click="handleClose">×</button>
        </div>

        <!-- 聊天记录 -->
        <div class="chat-body">
          <div
            v-if="filteredChatMessages.length"
            v-for="(msg, index) in filteredChatMessages"
            :key="index"
            :class="[
              'chat-message',
              msg.senderId == null ? 'ai-message' : 'user-message',
            ]"
            @click="openMessageMenu($event, msg)"
          >
            <div v-if="msg.selectedContent" class="quote-text">
              {{ msg.selectedContent }}
            </div>
            {{ msg.text }}
          </div>
          <div v-else class="no-messages">暂无聊天记录</div>
        </div>

        <!-- 输入框 -->
        <div class="chat-input">
          <div v-if="loading" class="thinking-message">AI正在思考中...</div>
          <div class="selected-content-above-input">
            <div class="quote-text">{{ truncatedContent }}</div>
            <button v-if="showMore" @click="toggleContentDisplay">...</button>
          </div>
          <!-- 替换 input 为 textarea -->
          <textarea
            v-model="chatInput"
            @keydown.enter.exact.prevent="sendChatMessage"
            @keydown.shift.enter.exact.prevent="handleNewLine"
            placeholder="输入消息..."
            class="chat-textarea"
          ></textarea>
          <button @click="sendChatMessage">发送</button>
        </div>

        <!-- 点击保存注解菜单 -->
        <div
          v-if="messageMenu.visible"
          class="message-context-menu"
          :style="{ left: messageMenu.x + 'px', top: messageMenu.y + 'px' }"
        >
          <button @click="saveAsAnnotation">保存为注解</button>
        </div>

        <!-- Drawer 侧边栏 -->
        <div
          v-if="drawerVisible"
          class="drawer-overlay"
          @click.self="closeDrawer"
        >
          <div class="drawer-panel">
            <h3>历史对话</h3>
            <div
              v-for="session in chatSessions"
              :key="session.sessionId"
              class="session-item"
              @click="selectSession(session.sessionId)"
            >
              {{ session.lastMessage.slice(0, 30)
              }}{{ session.lastMessage.length > 30 ? '...' : '' }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import {
  connectSocket,
  sendSocketMessage,
  closeSocket,
} from '@/utils/websocket.js'
import { useAccountStore } from '@/stores/useAccountStore'
import { getAiSessions, getAiMessages, createNewSession } from '@/apis/book'
import { useRoute } from 'vue-router'

const route = useRoute()

// --- 定义 props 和 emits ---
const props = defineProps({
  visible: Boolean,
  selectedContent: String,
  chapterId: Number,
})
const emit = defineEmits(['close', 'clear-selected-content', 'save-annotation'])

// --- 账号信息、WebSocket URL ---
const accountStore = useAccountStore()
const userId = accountStore.uid
const wsUrl = `ws://localhost:8080/ws/aiRead-socket?userId=${userId}`

// --- 核心数据 ---
const chatInput = ref('')
const chatMessages = ref([]) // 当前选中session的消息列表
const chatSessions = ref([]) // 历史session列表
const currentSessionId = ref(null) // 当前打开的sessionId
const loading = ref(false)

// --- 侧边栏 Drawer 控制 ---
const drawerVisible = ref(false)

// --- 输入区相关 ---
const showMore = ref(false)
const truncatedContent = computed(() => {
  if (props.selectedContent.length > 100 && !showMore.value) {
    return props.selectedContent.substring(0, 100) + '...'
  }
  return props.selectedContent
})
const toggleContentDisplay = () => (showMore.value = !showMore.value)

// --- 过滤当前选中 session 的消息 ---
const filteredChatMessages = computed(() => {
  return chatMessages.value.filter(
    (msg) => msg.sessionId === currentSessionId.value
  )
})

// --- 获取 AI 历史会话列表 ---
const fetchChatSessions = async () => {
  try {
    const res = await getAiSessions(userId)
    if (res && res.data) {
      chatSessions.value = res.data
        .map((item) => ({
          sessionId: item.sessionId,
          lastMessage: item.lastMessage || '',
          updateTime: new Date(item.postTime).getTime(),
        }))
        .sort((a, b) => b.updateTime - a.updateTime) // 按更新时间倒序
    }
  } catch (err) {
    console.error('❌ 获取AI会话失败:', err)
  }
}

// --- 获取指定session的聊天记录 ---
const fetchChatMessages = async (sessionId) => {
  try {
    const res = await getAiMessages(sessionId)
    if (res && res.data) {
      chatMessages.value = res.data.map((item) => ({
        sessionId: sessionId,
        senderId: item.senderId, // null代表AI，正常用户id代表人
        text: item.content,
        postTime: new Date(item.time).getTime(),
      }))
    }
  } catch (err) {
    console.error('❌ 获取聊天记录失败:', err)
  }
}

// --- 打开/关闭 Drawer ---
const openDrawer = () => (drawerVisible.value = true)
const closeDrawer = () => (drawerVisible.value = false)

// --- 切换当前 Session ---
const selectSession = async (sessionId) => {
  currentSessionId.value = sessionId
  await fetchChatMessages(sessionId)
  nextTick(() => {
    scrollToBottom()
  })
}

// --- 处理收到的 WebSocket 消息 ---
const handleIncomingMessage = (msg) => {
  chatMessages.value.push({
    sessionId: currentSessionId.value,
    senderId: null, // 接收的实时消息都是AI
    text: msg.content || JSON.stringify(msg),
    chapterId: props.chapterId || 0,
  })
  updateSession()
  loading.value = false
  nextTick(() => {
    scrollToBottom()
  })
}

// --- 发送自己的消息 ---
const sendChatMessage = async () => {
  loading.value = true
  console.log('当前session', currentSessionId.value)

  // 如果当前 sessionId 为空，则创建一个新会话
  if (!currentSessionId.value) {
    const newSession = await createNewSession() // 请求后端创建新会话
    currentSessionId.value = newSession.data // 设置新的 sessionId
  }

  // 确保 sessionId 已经设置，再发送消息
  if (currentSessionId.value) {
    // 发送用户输入的消息
    chatMessages.value.push({
      sessionId: currentSessionId.value,
      senderId: userId,
      text: chatInput.value,
      selectedContent: props.selectedContent,
    })

    sendSocketMessage({
      sessionId: currentSessionId.value,
      userId: userId,
      content: chatInput.value,
      selectedContent: props.selectedContent,
    })

    updateSession()
    chatInput.value = '' // 清空输入框
    nextTick(() => {
      scrollToBottom()
    })
  } else {
    console.error('Session ID is still null, cannot send message.')
  }
}

// --- 更新 session 最近一条消息 ---
const updateSession = () => {
  const session = chatSessions.value.find(
    (s) => s.sessionId === currentSessionId.value
  )
  const lastMsg = chatMessages.value
    .filter((m) => m.sessionId === currentSessionId.value)
    .slice(-1)[0]
  if (session && lastMsg) {
    session.lastMessage = lastMsg.text
    session.updateTime = Date.now()
  }
}

const createNewChat = async () => {
  chatMessages.value = []
  currentSessionId.value = null
  console.log(currentSessionId.value)
}

// --- 关闭对话框 ---
const handleClose = () => {
  emit('clear-selected-content')
  chatInput.value = ''
  emit('close')
}

// --- 消息右键弹出保存菜单 ---
const messageMenu = ref({ visible: false, x: 0, y: 0, selectedMessage: null })
const openMessageMenu = (event, msg) => {
  const rect = event.currentTarget.getBoundingClientRect()
  messageMenu.value = {
    visible: true,
    x: rect.left,
    y: rect.bottom + 4,
    selectedMessage: msg,
  }
}
const saveAsAnnotation = () => {
  emit('save-annotation', messageMenu.value.selectedMessage)
  messageMenu.value.visible = false
}

// --- 点击空白区域隐藏右键菜单 ---
const handleDocumentClick = (e) => {
  if (
    !e.target.closest('.chat-message') &&
    !e.target.closest('.message-context-menu')
  ) {
    messageMenu.value.visible = false
  }
}

// --- 生命周期钩子 ---
onMounted(async () => {
  connectSocket(wsUrl, handleIncomingMessage)
  document.addEventListener('click', handleDocumentClick)

  await fetchChatSessions() // 拉session列表（侧边栏需要）
  drawerVisible.value = true
})

onBeforeUnmount(() => {
  closeSocket()
  document.removeEventListener('click', handleDocumentClick)
})
const scrollToBottom = () => {
  const chatBody = document.querySelector('.chat-body')
  if (chatBody) {
    chatBody.scrollTop = chatBody.scrollHeight
  }
}
</script>

<style scoped>
.ai-chat-modal {
  position: fixed;
  right: 80px;
  top: 120px;
  width: 340px;
  height: 480px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  z-index: 3000;
  display: flex;
  flex-direction: column;
}

.chat-header {
  background: #409eff;
  color: #fff;
  padding: 10px;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
}

.ai-title {
  flex-grow: 1;
  text-align: center;
  font-size: 18px;
}

.drawer-btn,
.new-chat-btn,
.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
  position: relative; /* Ensures tooltip is positioned relative to the button */
}

.new-chat-btn {
  position: relative;
}

.drawer-btn:hover .tooltip,
.new-chat-btn:hover .tooltip {
  visibility: visible;
}

.tooltip {
  visibility: hidden;
  position: absolute;
  top: -25px; /* Move the tooltip above the button */
  left: 50%;
  transform: translateX(-50%);
  background-color: #333;
  color: white;
  font-size: 12px;
  padding: 5px;
  border-radius: 4px;
  white-space: nowrap;
  z-index: 1000;
}

.chat-body {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.chat-message {
  margin-bottom: 10px;
  word-break: break-word;
  cursor: pointer;
}

.user-message {
  align-self: flex-end;
  background-color: #e1f5fe;
  border-radius: 8px;
  padding: 5px 10px;
}

.ai-message {
  align-self: flex-start;
  background-color: #f1f1f1;
  border-radius: 8px;
  padding: 5px 10px;
}

.chat-textarea {
  width: 100%;
  min-height: 40px;
  max-height: 120px;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 6px;
  resize: vertical; /* 允许垂直调整大小 */
  overflow-y: auto; /* 内容超出时显示滚动条 */
  white-space: pre-wrap; /* 保留换行 */
  word-wrap: break-word; /* 允许单词断行 */
  line-height: 1.5;
}

/* 调整原有样式 */
.chat-input {
  border-top: 1px solid #ccc;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 8px; /* 增加元素间距 */
}

.chat-input button {
  align-self: flex-end; /* 按钮右对齐 */
  padding: 6px 20px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
}

.chat-input button:hover {
  background: #66b1ff;
}

.selected-content-above-input {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  white-space: normal;
  margin-bottom: 8px;
}

.selected-content-above-input button {
  background: none;
  border: none;
  color: #409eff;
  cursor: pointer;
  font-size: 14px;
}

.chat-input input {
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 6px;
}

.chat-input button {
  margin-top: 8px;
  padding: 6px 12px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.message-context-menu {
  position: fixed;
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 4000;
  padding: 8px 0;
  min-width: 140px;
  display: flex;
  flex-direction: column;
}

.message-context-menu button {
  background: none;
  border: none;
  padding: 10px 20px;
  text-align: left;
  width: 100%;
  font-size: 14px;
  color: #333;
  cursor: pointer;
  transition: background-color 0.2s, color 0.2s;
}

.message-context-menu button:hover {
  background: #f0f8ff;
  color: #409eff;
  font-weight: 500;
}

.no-messages {
  color: #999;
  text-align: center;
  margin-top: 30px;
  font-size: 14px;
}

.quote-text {
  position: relative;
  padding-left: 12px;
  margin: 8px 0;
  font-style: italic;
  color: #d3d3d3;
}

.drawer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3);
  z-index: 4000;
  display: flex;
}

.drawer-panel {
  width: 260px;
  background: white;
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  box-shadow: 4px 0 12px rgba(0, 0, 0, 0.2);
}

.session-item {
  padding: 12px 0;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.session-item:hover {
  background: #f9f9f9;
}

.ai-assistant-icon {
  position: fixed;
  top: 120px;
  right: 20px;
  width: 50px;
  height: 50px;
  z-index: 3000;
  cursor: pointer;
  transition: transform 0.2s;
}

.ai-assistant-icon:hover {
  transform: scale(1.1);
}

.thinking-message {
  color: #999;
  text-align: center;
  font-size: 14px;
  margin-top: 10px;
}
</style>
